package com.excel.poi.sax.inter;

import com.excel.poi.sax.AnalysisEventListener;
import com.excel.poi.sax.BaseSaxAnalyser;
import com.excel.poi.sax.XlsSaxAnalyser;
import com.excel.poi.sax.XlsxSaxAnalyser;

import java.io.InputStream;

/**
 * @author zw
 * @Description excel解析实现
 * @create /2022/3/25
 */
public class ExcelAnalyserImpl implements ExcelAnalyser {
     //内容解析
    private AnalysisContextImpl analysisContext;

    private BaseSaxAnalyser saxAnalyser;

    public ExcelAnalyserImpl(InputStream inputStream,Class c1,AnalysisEventListener eventListener, boolean trim) {
        analysisContext = new AnalysisContextImpl(inputStream,c1, eventListener, trim);
    }

    @Override
    public void analysis() throws Exception {
        //2.1 将流和监听器 适配给 Xlsx对象或者Xls对象
        BaseSaxAnalyser saxAnalyser = getSaxAnalyser();
        //追加监听器
        appendListeners(saxAnalyser);
        saxAnalyser.execute();
        analysisContext.getEventListener().doAfterAllAnalysed(analysisContext);
    }

    /**
     * 将流和监听器 适配给 Xlsx对象或者Xls对象
     *  2 拆分每个sheet
     * @return
     * @throws Exception
     */
    private BaseSaxAnalyser getSaxAnalyser() throws Exception {
        if (saxAnalyser != null) {
            return this.saxAnalyser;
        }
        try {
                try {
                    this.saxAnalyser = new XlsxSaxAnalyser(analysisContext);
                } catch (Exception e) {
                    this.saxAnalyser = new XlsSaxAnalyser(analysisContext);
                }

        } catch (Exception e) {
            throw new Exception(e);
        }
        return this.saxAnalyser;
    }
    private void appendListeners(BaseSaxAnalyser saxAnalyser) {
        saxAnalyser.cleanAllListeners();
     /*   if (analysisContext.getCurrentSheet() != null && analysisContext.getCurrentSheet().getClazz() != null) {
            saxAnalyser.appendLister("model_build_listener", new ModelBuildEventListener());
        }*/
        if (analysisContext.getEventListener() != null) {
            saxAnalyser.appendLister("user_define_listener", analysisContext.getEventListener());
        }
    }
}
